<?php
/*
 * @Description    : redis缓存
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2021-04-16 16:48:24
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-05-11 17:09:16
 */

namespace app\common;

use app\common\model\AdsCate;
use app\common\model\CaptchaModel;
use app\common\model\SysAlipayEcmpay;
use app\common\model\SysAlipaySetting;
use app\common\model\SysPaymentSetting;
use app\common\model\SysSetting;
use app\common\model\SysSmsSetting;
use app\common\model\SysWxpayEcmpay;
use app\common\model\SysWxpaySetting;
use app\common\model\UserSetting;
use app\common\model\Version;
use app\common\service\QlRedis;
use app\lib\exception\ApiException;
use think\facade\Db;

class RedisCache
{
    protected static $redis;
    public function __construct()
    {
        self::$redis = new QlRedis;
    }
    public function getSetQrcodeLoginUUID($key, $data = '', $expireTime = 300)
    {
        $tokenInfo = '';
        if (!empty($data) && !empty($key)) {
            self::$redis->set('libs:loginUUID:' . $key, $data, $expireTime);
        } else {
            $cacheTTL = self::$redis->ttl('libs:loginUUID:' . $key);
            if ($cacheTTL === -1 || $cacheTTL > $expireTime) {
                self::$redis->del('libs:loginUUID:' . $key);
            }
            if (self::$redis->exists('libs:loginUUID:' . $key) > 0) {
                $data_s = self::$redis->get('libs:loginUUID:' . $key);
                $tokenInfo = $data_s;
            }
            return $tokenInfo;
        }
    }
    public function getSetInviterUid($uid, $data = '', $expireTime = 5184000)
    {
        $tokenInfo = '';
        if (!empty($data) && !empty($uid)) {
            self::$redis->set('libs:inviter:' . $uid, $data, $expireTime);
        } else {
            $cacheTTL = self::$redis->ttl('libs:inviter:' . $uid);
            if ($cacheTTL === -1 || $cacheTTL > $expireTime) {
                self::$redis->del('libs:inviter:' . $uid);
            }
            if (self::$redis->exists('libs:inviter:' . $uid) > 0) {
                $data_s = self::$redis->get('libs:inviter:' . $uid);
                $tokenInfo = $data_s;
            }
            return $tokenInfo;
        }
    }
    public function getSetFqfCache($key, $data = '', $expireTime = 600)
    {
        $tokenInfo = '';
        if (!empty($data) && !empty($key)) {
            self::$redis->set('libs:contract:fqf:' . $key, $data, $expireTime);
        } else {
            $cacheTTL = self::$redis->ttl('libs:contract:fqf:' . $key);
            if ($cacheTTL === -1 || $cacheTTL > $expireTime) {
                self::$redis->del('libs:contract:fqf:' . $key);
            }
            if (self::$redis->exists('libs:contract:fqf:' . $key) > 0) {
                $data_s = self::$redis->get('libs:contract:fqf:' . $key);
                $tokenInfo = $data_s;
            }
            return $tokenInfo;
        }
    }
    public function getSetVerifyCache($key, $data = '', $expireTime = 86400)
    {
        $tokenInfo = '';
        if (!empty($data) && !empty($key)) {
            self::$redis->set('libs:contract:verify:' . $key, $data, $expireTime);
        } else {
            $cacheTTL = self::$redis->ttl('libs:contract:verify:' . $key);
            if ($cacheTTL === -1 || $cacheTTL > $expireTime) {
                self::$redis->del('libs:contract:verify:' . $key);
            }
            if (self::$redis->exists('libs:contract:verify:' . $key) > 0) {
                $data_s = self::$redis->get('libs:contract:verify:' . $key);
                $tokenInfo = $data_s;
            }
            return $tokenInfo;
        }
    }
    /**
     * 读取设置验证码Token
     */
    public function getSetRotateCaptchaToken($key, $token = '')
    {
        if (!empty($key) && !empty($token)) {
            self::$redis->set('libs:verify:' . $key, $token, config('app.SYS_STATIC.redis_expire'));
        } else {
            $value = self::$redis->get('libs:verify:' . $key);
            self::$redis->del('libs:verify:' . $key);
            return $value;
        }
    }
    public function getSetSRVerifyUrl($key, $token = '')
    {
        if (!empty($key) && !empty($token)) {
            self::$redis->set('libs:sr:verify:' . $key, $token, config('app.SYS_STATIC.redis_expire'));
        } else {
            $value = self::$redis->get('libs:sr:verify:' . $key);
            return $value;
        }
    }
    public function getSetCaptchaSecret($key, $expire = -1, $secret = '')
    {
        $expire = $expire > 0 ? $expire : config('app.SYS_STATIC.redis_expire');
        $cacheTTL = self::$redis->ttl('libs:verify:secret:' . $key);
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('libs:verify:secret:' . $key);
        }
        if (!empty($secret)) {
            $items = $secret;
            self::$redis->set('libs:verify:secret:' . $key, $items, $expire);
            self::$redis->set('libs:verify:change_secret:' . $key, 1, $expire);
        } else {
            $hasOldSecret = self::$redis->get('libs:verify:change_secret:' . $key);
            if ($hasOldSecret == 1) {
                $items = self::$redis->get('libs:verify:secret:' . $key);
                $dbItem = CaptchaModel::where('app_id', $key)->find();
                if (!empty($dbItem)) {
                    $items = $items . ',' . $dbItem['app_secret'];
                }
            } else {
                if (self::$redis->exists('libs:verify:secret:' . $key) > 0) {
                    $items = self::$redis->get('libs:verify:secret:' . $key);
                } else {
                    $hasSecret = CaptchaModel::where('app_id', $key)->find();
                    if (!empty($hasSecret)) {
                        $items = $hasSecret['app_secret'];
                    self::$redis->set('libs:verify:secret:' . $key, $items, $expire);
                    }
                }
            }
        }
        if (empty($items)) {
            throw new ApiException('应用配置为空1');
        }
        return $items;
    }
    public function getSetCaptchaInfo($key, $expire = -1)
    {
        $expire = $expire > 0 ? $expire : config('app.SYS_STATIC.redis_expire');
        $cacheTTL = self::$redis->ttl('libs:verify:info:' . $key);
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('libs:verify:info:' . $key);
        }
        if (self::$redis->exists('libs:verify:info:' . $key) > 0) {
            $items = self::$redis->get('libs:verify:info:' . $key);
            $items = json_decode($items,true);
        } else {
            $items = CaptchaModel::where('app_id', $key)->find();
            if (!empty($items)) {
                self::$redis->set('libs:verify:info:' . $key, json_encode($items), $expire);
            }
            
        }
        if (empty($items)) {
            throw new ApiException('应用配置为空');
        }
        return $items;
    }
    public function getVersionInfo($version_id,$field = '*')
    {
        $expire = config('app.SYS_STATIC.redis_expire');
        $cacheTTL = self::$redis->ttl('libs:version:info:' . $version_id.':'.md5($field));
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('libs:version:info:' .$version_id . ':' . md5($field));
        }
        if (self::$redis->exists('libs:version:info:' .$version_id . ':' . md5($field)) > 0) {
            $items = self::$redis->get('libs:version:info:' .$version_id . ':' . md5($field));
            $items = json_decode($items,true);
        } else {
            $items = Version::field($field)->where('id', $version_id)->find();
            if (!empty($items)) {
                self::$redis->set('libs:version:info:' .$version_id . ':' . md5($field), json_encode($items), $expire);
            }
        }
        if (empty($items)) {
            throw new ApiException('会员版本不存在');
        }
        return $items;
    }
    public function getUserSetting($uid, $expire = -1)
    {
        $expire = $expire > 0 ? $expire : config('app.SYS_STATIC.redis_expire');
        $cacheTTL = self::$redis->ttl('libs:userSetting:info:' . $uid);
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('libs:userSetting:info:' . $uid);
        }
        if (self::$redis->exists('libs:userSetting:info:' . $uid) > 0) {
            $items = self::$redis->get('libs:userSetting:info:' . $uid);
            $items = json_decode($items,true);
        } else {
            $items = UserSetting::where('uid', $uid)->find();
            if (!empty($items)) {
                self::$redis->set('libs:userSetting:info:' . $uid, json_encode($items), $expire);
            }
        }
        if (empty($items)) {
            throw new ApiException('用户配置为空');
        }
        return $items;
    }
    public function getSysSetting()
    {
        $expire = config('app.SYS_STATIC.redis_expire');
        $cacheTTL = self::$redis->ttl('dever_sys:setting','full');
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('dever_sys:setting', 'full');
        }
        if (self::$redis->exists('dever_sys:setting', 'full') > 0) {
            $items = self::$redis->get('dever_sys:setting', 'full');
            $items = json_decode($items,true);
        } else {
            $items = SysSetting::where('id', 1)->find();
            if (!empty($items)) {
                self::$redis->set('dever_sys:setting', json_encode($items),$expire, 'full');
            }
        }
        if (empty($items)) {
            throw new ApiException('系统配置为空');
        }
        return $items;
    }
    /**
     * 读取系统支付项配置
     */
    public static function getSysPaymentSetting()
    {
        $cacheTTL = self::$redis->ttl('system:payment:setting');
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('system:payment:setting');
        }
        if (self::$redis->exists('system:payment:setting') > 0) {
            $items = self::$redis->get('system:payment:setting');
            $items = json_decode($items, true);
        } else {
            $items = SysPaymentSetting::where('id', 1)->find();
            self::$redis->set('system:payment:setting', json_encode($items), config('app.SYS_STATIC.redis_expire'));
        }
        if (empty($items)) {
            throw new ApiException('系统配置为空');
        }
        return $items;
    }
    /**
     * 读取广告分类
     */
    public static function getAdsCate($id)
    {
        $cacheTTL = self::$redis->ttl('ads:cate:'.$id);
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('ads:cate:'.$id);
        }
        if (self::$redis->exists('ads:cate:'.$id) > 0) {
            $items = self::$redis->get('ads:cate:'.$id);
            $items = json_decode($items, true);
        } else {
            $items = AdsCate::where('id_var', $id)->find();
            self::$redis->set('ads:cate:'.$id, json_encode($items), config('app.SYS_STATIC.redis_expire'));
        }
        if (empty($items)) {
            throw new ApiException('广告分类不存在或已删除');
        }
        return $items;
    }
    public function clearAdsCate($id)
    {
        self::$redis->del('ads:cate:'.$id);
        self::$redis->del('dever_ads:cate:'.$id,'full');
    }
    public static function getSysSmsSetting()
    {
        $cacheTTL = self::$redis->ttl('system:sms:setting');
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('system:sms:setting');
        }
        if (self::$redis->exists('system:sms:setting') > 0) {
            $items = self::$redis->get('system:sms:setting');
            $items = json_decode($items, true);
        } else {
            $items = SysSmsSetting::where('id', 1)->find();
            self::$redis->set('system:sms:setting', json_encode($items), config('app.SYS_STATIC.redis_expire'));
        }
        if (empty($items)) {
            throw new ApiException('短信配置为空');
        }
        return $items;
    }
    public static function getSysPaySetting($type)
    {
        $cacheTTL = self::$redis->ttl('system:pay:setting:' . $type);
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('system:pay:setting:' . $type);
        }
        $items = [];
        if (self::$redis->exists('system:pay:setting:' . $type) > 0) {
            $items = self::$redis->get('system:pay:setting:' . $type);
            $items = json_decode($items, true);
        } else {
            $resultPayment = self::getSysPaymentSetting();
            if (isset($resultPayment['pay_platform']) && $resultPayment['pay_platform'] == 'ecmpay') {
                if ($type == 'alipay') {
                    $items = SysAlipayEcmpay::where('id', 1)->find()->toArray();
                } elseif ($type == 'wxpay') {
                    $items = SysWxpayEcmpay::where('id', 1)->find()->toArray();
                }
            } else {
                if ($type == 'alipay') {
                    $items = SysAlipaySetting::where('id', 1)->find()->toArray();
                } elseif ($type == 'wxpay') {
                    $items = SysWxpaySetting::where('id', 1)->find()->toArray();
                }
            }
            self::$redis->set('system:pay:setting:' . $type, json_encode($items), config('app.SYS_STATIC.redis_expire'));
        }
        if (empty($items)) {
            throw new ApiException('支付配置为空');
        }
        return $items;
    }
    public static function getPushServerInfo($id)
    {
        $cacheTTL = self::$redis->ttl('dever:push:server:' . $id, 'full');
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('dever:push:server:' . $id, 'full');
        }
        $items = [];
        if (self::$redis->exists('dever:push:server:' . $id, 'full') > 0) {
            $items = self::$redis->get('dever:push:server:' . $id, 'full');
            $items = json_decode($items, true);
        } else {
            $items = Db::connect('mongodb')->name('push_server_list')->where('_id', $id)->find();
            self::$redis->set('dever:push:server:' . $id, json_encode($items), config('app.SYS_STATIC.redis_expire'), 'full');
        }
        if (empty($items)) {
            throw new ApiException('推送配置为空或不存在');
        }
        return $items;
    }
    public static function getFileServerInfo($id)
    {
        $cacheTTL = self::$redis->ttl('dever:file:server:' . $id, 'full');
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('dever:file:server:' . $id, 'full');
        }
        $items = [];
        if (self::$redis->exists('dever:file:server:' . $id, 'full') > 0) {
            $items = self::$redis->get('dever:file:server:' . $id, 'full');
            $items = json_decode($items, true);
        } else {
            $items = Db::connect('mongodb')->name('file_server_list')->where('_id', $id)->find();
            self::$redis->set('dever:file:server:' . $id, json_encode($items), config('app.SYS_STATIC.redis_expire'), 'full');
        }
        if (empty($items)) {
            throw new ApiException('文件存储配置为空或不存在');
        }
        return $items;
    }
    public static function getEmailServerInfo($id)
    {
        $cacheTTL = self::$redis->ttl('dever:email:server:' . $id, 'full');
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('dever:email:server:' . $id, 'full');
        }
        $items = [];
        if (self::$redis->exists('dever:email:server:' . $id, 'full') > 0) {
            $items = self::$redis->get('dever:email:server:' . $id, 'full');
            $items = json_decode($items, true);
        } else {
            $items = Db::connect('mongodb')->name('email_server_list')->where('_id', $id)->find();
            self::$redis->set('dever:email:server:' . $id, json_encode($items), config('app.SYS_STATIC.redis_expire'), 'full');
        }
        if (empty($items)) {
            throw new ApiException('邮件服务器配置为空或不存在');
        }
        return $items;
    }
    public static function getLogSiteInfo($id)
    {
        $cacheTTL = self::$redis->ttl('dever:log:site:' . $id, 'full');
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('dever:log:site:' . $id, 'full');
        }
        $items = [];
        if (self::$redis->exists('dever:log:site:' . $id, 'full') > 0) {
            $items = self::$redis->get('dever:log:site:' . $id, 'full');
            $items = json_decode($items, true);
        } else {
            $items = Db::connect('mongodb')->name('log_site_list')->where('_id', $id)->find();
            self::$redis->set('dever:log:site:' . $id, json_encode($items), config('app.SYS_STATIC.redis_expire'), 'full');
        }
        if (empty($items)) {
            throw new ApiException('日志站点配置不存在');
        }
        return $items;
    }
    public static function getSmsServerInfo($id)
    {
        $cacheTTL = self::$redis->ttl('dever:sms:server:' . $id, 'full');
        if ($cacheTTL === -1 || $cacheTTL > config('app.SYS_STATIC.redis_expire')) {
            self::$redis->del('dever:sms:server:' . $id, 'full');
        }
        $items = [];
        if (self::$redis->exists('dever:sms:server:' . $id, 'full') > 0) {
            $items = self::$redis->get('dever:sms:server:' . $id, 'full');
            $items = json_decode($items, true);
        } else {
            $items = Db::connect('mongodb')->name('sms_server_list')->where('_id', $id)->find();
            self::$redis->set('dever:sms:server:' . $id, json_encode($items), config('app.SYS_STATIC.redis_expire'), 'full');
        }
        if (empty($items)) {
            throw new ApiException('短信配置为空或不存在');
        }
        return $items;
    }
    public static function getMpWxInfo($mw_id)
    {
        $tag = substr($mw_id, 0, 2);
        if (strtolower($tag) == 'mw') {
            $where['_id'] = $mw_id;
        } else {
            $where['app_id'] = $mw_id;
        }
        $infoData = Db::connect('mongodb')->name('mp_weixin')->where($where)->find();
        $infoData = json_decode(json_encode($infoData), true);
        if (empty($infoData)) {
            throw new ApiException(-1, '对应公众号不存在');
        }
        $infoData['event_url'] = isset($infoData['event_url']) ? $infoData['event_url'] : '';
        return $infoData;
    }
    public static function getWsServer($ws_id)
    {
        $where['_id'] = $ws_id;
        $infoData = Db::connect('mongodb')->name('socket_io')->where($where)->find();
        $infoData = json_decode(json_encode($infoData), true);
        if (empty($infoData)) {
            throw new ApiException(-1, '对应实时推送配置不存在');
        }
        return $infoData;
    }
    public static function getMxAppInfo($ma_id)
    {
        $tag = substr($ma_id, 0, 2);
        if (strtolower($tag) == 'wa') {
            $where['_id'] = $ma_id;
        } else {
            $where['app_id'] = $ma_id;
        }
        $infoData = Db::connect('mongodb')->name('mp_miniapp')->where($where)->find();
        $infoData = json_decode(json_encode($infoData), true);
        if (empty($infoData)) {
            throw new ApiException(-1, '对应小程序不存在');
        }
        return $infoData;
    }
    public static function getWxWorkInfo($ww_id)
    {
        $where['$or'] = [];
        $where['$or'][] = ['_id' => $ww_id];
        $where['$or'][] = ['crop_id' => $ww_id];
        $infoData = Db::connect('mongodb')->name('mp_work')->where($where)->find();
        $infoData = json_decode(json_encode($infoData), true);
        if (empty($infoData)) {
            throw new ApiException(-1, '企业微信不存在');
        }
        return $infoData;
    }
}
